using System.Collections.Generic;
using System.Linq;
using NopSolutions.NopCommerce.BusinessLogic.Products.Specs;

namespace NopSolutions.NopCommerce.LuceneHelper.Tasks
{
    public class SpecificationsUpdateTask : BaseTask<SpecificationsUpdateTask>
    {
        #region Private

        private bool _updateProducts = true;
        private bool _updateOptions = true;

        #endregion

        #region Constructors

        public SpecificationsUpdateTask(bool updateProducts, bool updateOptions)
        {
            _updateProducts = updateProducts;
            _updateOptions = updateOptions;
        }

        #endregion

        #region Properties

        public bool UpdateProducts
        {
            get { return _updateProducts; }
            set { _updateProducts = value; }
        }

        public bool UpdateOptions
        {
            get { return _updateOptions; }
            set { _updateOptions = value; }
        }

        #endregion

        #region Task

        public override void DoTask(IndexManager indexManager, SearchManager searchManager, IndexWriterWrapper indexer)
        {
            foreach (var task in
                DatabaseHelper.GetAllMappedAttributes().Select(specificationAttribute => new SpecificationUpdateTask(specificationAttribute.SpecificationAttributeId, UpdateProducts, UpdateOptions)))
            {
                task.DoTask(indexManager, searchManager, indexer);
            }
        }

        public override LuceneIndexType IndexType
        {
            get { return LuceneIndexType.SpecificationAttributes; }
        }

        public override void AddToQueue(IList<ITask> tasks)
        {
            if (!tasks.Contains(this))
                tasks.Add(this);
        }

        public override bool RebuildIndex
        {
            get { return true; }
        }

        public override IEnumerable<System.Func<SpecificationsUpdateTask, object>> ComparableProperties()
        {
            return new List<System.Func<SpecificationsUpdateTask, object>> { x => x.UpdateProducts, x => x.UpdateOptions };
        }

        public override void UpdateTask(SpecificationsUpdateTask newTask)
        {
            if (!UpdateProducts)
            {
                UpdateProducts = newTask.UpdateProducts;
            }
            if (!UpdateOptions)
            {
                UpdateOptions = newTask.UpdateOptions;
            }
        } 

        #endregion
    }
}
